<template>
  <div id="approvalFlow">
    <filters
      block
      :form="searchForm"
      :filterData="filterData"
      @confirm="changePage(1)"
    />
    <div class="container">
      <DataTable
        rowKey="id"
        :btns="btns"
        :tableData="Data"
        :tableColumn="tableColumn"
        :pageConfig="pageConfig"
        @refresh="getList"
      />
    </div>
    <CommonDialog
      :rows="rows"
      :form="form"
      :title="tableType === 'add' ? '新增' : '编辑'"
      :visible="visible"
      @hideDialog="visible = false"
      @confirm="confirmHandle"
    >
      <template #rroleAdminUserAddList>
        <a-tag
          v-for="(item, index) in checkCopySendList" :key="index"
          closable
          @close.prevent="handleDeleteTag(2, item, index)"
        >
          {{item.label}}
        </a-tag>
        <a-button
          type="primary"
          shape="circle"
          icon="plus"
          ghost
          @click="handleShowModal"
          size="small"
        />
      </template>
    </CommonDialog>
    <!-- 添加审批人-->
    <a-modal
      title="添加审批人"
      :visible="dialog.visibleCopySend"
      class="common-dialog flow-detail"
      width="520px"
      :afterClose="copySendAfterClose"
      @cancel="dialog.visibleCopySend = false"
    >
      <div>
        <div class="flex no-center">
          <div class="choose">
            <a-row type="flex" justify="space-between">
              <a-col>
                <div class="radio-title">选择角色</div>
              </a-col>
              <a-col>
                <a-checkbox
                  :checked="checkedOne"
                  @change="handleCheckAllOne"
                >
                  全选
                </a-checkbox>
              </a-col>
            </a-row>
            <a-checkbox
              v-for="(item, index) in copySend"
              :checked="item.checked"
              :key="index"
              :value="item.value"
              @change="handleCheckAll(item, $event)"
            >
              <span class="send-check-span" @click.prevent="handleRoleFocus(item)">{{
                item.label
              }}</span>
            </a-checkbox>
          </div>
          <div class="gm">
            <a-row type="flex" justify="space-between">
              <a-col>
                <div class="radio-title">{{ gmTitileCopySend }}</div>
              </a-col>
              <a-col>
                <a-checkbox
                  :checked="checkedTwo"
                  @change="handleCheckAllTwo"
                >
                  全选
                </a-checkbox>
              </a-col>
            </a-row>
              <a-checkbox
                v-for="(item, index) in rightcopySendList"
                :key="index"
                :value="item.value"
                :checked="item.checked"
                @change="handleChangeChecked(item, $event, 'send')"
                >{{ item.label }}
              </a-checkbox>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <a-button @click="handleShowDialog">取 消</a-button>
        <a-button type="primary" @click="handleCopySendConfirm">确 定</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';

@Component
export default class approvalFlow extends Vue {
  searchForm: any = {
    date: [],
    type: undefined,
    status: undefined
  };
  filterData: any = {
    type: {
      label: '审批类型',
      type: 'select',
      width: 200,
      template: {
        placeholder: '请选择审批类型',
        clearable: true,
        filterable: true,
        options: [
          {
            label: '协同验收',
            value: 1
          }
        ]
      }
    },
    status: {
      label: '状态',
      type: 'select',
      width: 200,
      template: {
        placeholder: '请选择状态',
        clearable: true,
        filterable: true,
        options: [
          {
            label: '启用',
            value: 1
          },
          {
            label: '禁用',
            value: 0
          }
        ]
      }
    },
    date: {
      label: '时间',
      type: 'daterange',
      template: {
        clearable: true
      }
    }
  };
  Data: any[] = [];
  tableColumn: any = {
    type: {
      label: '审批类型',
      width: 130,
      map: {
        1: '协同验收'
      }
    },
    approvePeople: {
      label: '审批人',
      hidden: true,
      width: 200
    },
    createTime: {
      label: '创建时间',
      width: 200
    },
    adminUser: {
      label: '创建人',
      width: 200
    },
    status: {
      label: '状态',
      type: 'switch',
      width: 200,
      callback: this.handleChangeStatus
    },
    action: {
      label: '操作',
      width: 250,
      template: [
        {
          tag: 'a',
          text: '编辑',
          callback: this.showDialog
        },
        {
          tag: 'a',
          text: '删除',
          confirm: this.handleDelete
        }
      ]
    }
  };
  pageConfig: any = {
    current: 1,
    total: 10,
    pageSize: 10,
    onChange: this.changePage
  };
  btns: any[] = [
    {
      label: '新增',
      icon: 'add',
      callback: this.showDialog
    }
  ];
  form: any = {
    type: undefined,
    rroleAdminUserAddList: [],
    status: undefined
  };
  get rows () {
    return {
      type: {
        label: '审批类型',
        el: 'select',
        placeholder: '请选择审批类型',
        options: [
          {
            label: '协同验收',
            value: 1
          }
        ],
        rules: [
          { required: true, message: '请选择审批类型', trigger: 'change' }
        ]
      },
      rroleAdminUserAddList: {
        label: '审批人',
        slot: true,
        rules: [
          { required: true, message: '请选择审批人', trigger: 'change' },
          { validator: this.checkAddList, trigger: 'change' }
        ]
      },
      status: {
        label: '状态',
        el: 'radio',
        option: [
          {
            label: '启用',
            value: 1
          },
          {
            label: '停用',
            value: 0
          }
        ],
        rules: [
          { required: true, message: '请选择审核状态', trigger: 'change' }
        ]
      }
    }
  }
  tableType: string = 'add'
  visible: boolean = false

  // 审批人modal
  copySend: any[] = [];
  rightcopySendList: any = []; // 抄送人右边数据
  checkCopySendList: any[] = []
  dialog: any = {
    visible: false,
    visibleCopySend: false,
    title: '添加审批人'
  };
  gmTitileCopySend: string = '';
  checkedOne: boolean = false // 左边全选
  checkedTwo: boolean = false // 右边全选

  checkAddList (rule: any, value: any, callback: any) {
    if (!this.checkCopySendList.length) {
      return callback(new Error('请选择审批人'))
    }
    callback()
  }
  init () {
    this.getList();
    this.getRoleList()
  }
  getList () {
    let { status, date, type } = this.searchForm;
    let [startTime, endTime] = this.$util.formatDate(date);
    let data = {
      status,
      type,
      startTime,
      endTime,
      page: this.pageConfig.current,
      size: this.pageConfig.pageSize
    };
    this.$api.approveListFetch(data).then((res: any) => {
      this.Data = res.data.records;
      this.pageConfig.total = res.data.total;
      if (!this.Data.length && this.pageConfig.current > 1) {
        --this.pageConfig.current;
        this.getList();
      }
    });
  }
  confirmHandle () {
    const form = Object.assign({}, this.form, {rroleAdminUserAddList: this.checkCopySendList})
    let api = this.tableType === 'add' ? 'approveAddFetch' : 'approveUpdateFetch'
    this.$api[api](form).then(() => {
      this.$message.success(`${this.tableType === 'add' ? '新增' : '编辑'}成功`)
      this.visible = false
      this.getList()
    })
  }
  // 显示选择审批人的dialog
  handleShowModal () {
    this.visible = false
    this.dialog.visibleCopySend = true
  }
  // 显示新增编辑的dialog
  handleShowDialog () {
    this.dialog.visibleCopySend = false
    this.visible = true
  }
  // 新增、编辑的dialog
  showDialog (row: any) {
    this.tableType = row ? 'edit' : 'add'
    this.form = row || {
      type: undefined,
      rroleAdminUserAddList: [],
      status: undefined
    }
    this.checkCopySendList = []
    this.rightcopySendList = this.copySend[0]?.children
    row && this.getDetail(row.id)
    if (!row) {
      // 重置状态
      this.copySend.forEach(item => {
        item.checked = false
        item.children && item.children.forEach((ele: any) => {
          ele.checked = false
        })
      })
      this.checkedOne = false
      this.checkedTwo = false
    }
    this.visible = true
  }
  // 编辑的详情
  getDetail (id: string) {
    this.$api.approveDetailFetch({id}).then(({data}: any) => {
      data.status = Number(data.status)
      // 抄送人
      this.checkCopySendList = data.rroleAdminUserAddList.map((item: any) => {
        item.checked = true
        item.label = item.user_name
        item.value = item.admin_id
        return item
      })
      // 抄送人主要是成员，和角色无关
      this.copySend.forEach((item) => {
        let arr = item.children.map((child: any) => { // 每个角色对应的成员数据
          // 和上面从接口返回来处理好的数据对比，找出对应的成员
          child.checked = (this.checkCopySendList.find(ele => ele.value === child.value) || { checked: false }).checked
          return child
        })
        // 判断处理后的children，是否角色下全选
        item.checked = arr.every((ele: any) => ele.checked === true)
      })
      this.checkedOne = this.copySend.every(item => item.checked)
      this.checkedTwo = this.rightcopySendList.every((item: any) => item.checked)
      this.form = data
    })
  }
  changePage (val: number) {
    this.pageConfig.current = val;
    this.getList();
  }
  handleDelete ({ id }: any) {
    this.$api.approveDeleteFetch({ id }).then(() => {
      this.$message.success('删除成功');
      this.getList();
    });
  }
  handleChangeStatus ({ status, id }: any, index: number) {
    const data = {
      id,
      status
    };
    this.$api.approveStatusFetch(data).then((res: any) => {
      this.$message.success('操作成功');
      this.getList();
    }).catch(() => {
      this.Data[index].status = !this.Data[index].status
    })
  }
  // 审批人modal
  getRoleList () {
    this.$api.approveListRoleFetch().then((res: any) => {
      let temp = res.data.map((item: any, index: number) => {
        // 处理角色下的成员
        const children = item.rroleAdminUserAddList.map((child: any) => {
          child.label = child.user_name
          child.value = child.admin_id // 用户标识
          child.checked = false
          return child
        })
        // 角色数据
        item.label = item.role_name
        item.value = item.role_id
        item.checked = false
        item.children = children
        return item
      })
      // 抄送人
      this.copySend = JSON.parse(JSON.stringify(temp))
    })
  }
  handleDeleteTag (type: number, item: any, index: number): void {
    this.checkCopySendList.splice(index, 1)
    // 编辑
    if (this.tableType === 'edit') {
      let idx = this.form.rroleAdminUserAddList.findIndex((ele: any) => item.value === ele.value)
      this.form.rroleAdminUserAddList.splice(idx, 1)
    }
    this.copySend.forEach((ele) => {
      let final = ele.children.find((child: any) => child.admin_id === item.admin_id)
      final && (final.checked = false)
    })
  }
  handleRoleFocus (item: any): void {
    this.rightcopySendList = item.children;
    this.gmTitileCopySend = item.label;
    this.checkedTwo = this.rightcopySendList.every((item: any) => item.checked)
  }
  // 左边copySend全选，即左右都全选
  handleCheckAllOne (e: any) {
    let checked = e.target.checked
    this.checkedOne = checked
    this.checkedTwo = checked
    this.copySend.forEach(item => {
      item.checked = checked
      item.children && item.children.forEach((ele: any) => {
        ele.checked = checked
      })
    })
  }
  handleCheckAllTwo (e: any) {
    let checked = e.target.checked
    this.checkedTwo = checked
    this.rightcopySendList.forEach((item: any) => {
      item.checked = checked
    })

    // 左边
    this.copySend.find(item => item.role_id === this.rightcopySendList[0].role_id).checked = checked
    this.checkedOne = this.copySend.every(item => item.checked)
  }
  // 抄送人角色选择，右边的子数组全选
  handleCheckAll (item: any, e: any) {
    let { checked } = e.target;
    item.checked = checked
    item.children.forEach((ele: any) => {
      ele.checked = checked
      return ele
    });
    this.checkedOne = this.copySend.every(item => item.checked)
    this.checkedTwo = this.rightcopySendList.every((item: any) => item.checked)
    checked && (this.rightcopySendList = item.children)
  }
  handleChangeChecked (item: any, e: any, type: string): void {
    let { checked } = e.target;
    item.checked = checked
    if (type) {
      // 处理抄送人右边的checkbox, 是否全选
      let flag = this.rightcopySendList.every((ele: any) => ele.checked === true)
      let role = this.copySend.find((ele) => ele.role_id === item.role_id)
      role && (role.checked = flag)
      this.checkedTwo = flag
      this.checkedOne = this.copySend.every(item => item.checked)
    }
  }
  // 抄送人modal的确定
  handleCopySendConfirm (): void {
    let temp: any[] = []
    this.copySend.map((item) => {
      item.children && item.children.forEach((child: any) => {
        if (child.checked) {
          temp.push(child)
        }
      })
    })
    this.checkCopySendList = JSON.parse(JSON.stringify(temp))
    this.form.rroleAdminUserAddList = JSON.parse(JSON.stringify(temp)) // 接口数据
    this.handleShowDialog()
  }
  // 抄送人madal关闭
  copySendAfterClose () {
    this.gmTitileCopySend = ''
    // 如果是取消，或者点击背景关闭。则选择的checkbox和tag保持一致
    this.copySend.map((item) => {
      item.children && item.children.forEach((child: any) => {
        this.checkCopySendList.forEach((ele) => {
          if (child.admin_id === ele.admin_id) {
            child.checked = ele.checked
          }
        })
      })
    })
  }
}
</script>

<style lang="scss" scoped>
.no-center {
  align-items: start;
}
.flow-detail {
  .ant-modal {
    .flex {
      padding: 10px 20px;
      border: 1px solid #c7c7c7;
      .choose,
      .gm {
        width: 50%;
        border-right: 1px solid #c7c7c7;
        /deep/.ant-radio-wrapper,
        /deep/.ant-checkbox-wrapper {
          display: block;
          margin-bottom: 10px;
          margin-left: 0;
        }
      }
      .gm {
        border: none;
        padding-left: 20px;
      }
    }
  }
}
.radio-title {
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 5px;
}
.send-check-span {
  padding: 5px 15px 5px 5px;
}
</style>
